package com.example.springboot.service.impl;

import com.example.springboot.Exception.ServiceException;
import com.example.springboot.common.Page;
import com.example.springboot.service.CartService;
import com.example.springboot.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车表(Cart)表服务实现类
 *
 * @author makejava
 * @since 2024-01-13 17:16:25
 */
@Service("cartService")
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private CartProductMapper cartProductMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public Page<Cart> getCarts(Integer currentPage, Integer pageSize, Integer userId) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;
            // 查询总记录数
            int status = 1;
            Integer totalCount = cartMapper.getTotalCountByUserId(userId, status);
            // 查询当前页数据
            List<Cart> carts = cartMapper.getCartsByUserId(startRow, pageSize, userId, status);
            Page<Cart> page = new Page<>();
            page.setList(carts);
            page.setTotal(totalCount);
            return page;
        } catch (Exception e) {
            throw new ServiceException("获取购物车列表失败");
        }
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        try {
            for (Integer id : ids) {
                cartMapper.deleteById(id);
            }
        } catch (Exception e) {
            throw new ServiceException("删除购物车失败");
        }
    }

    @Override
    public void deleteById(Integer id) {
        try {
            cartMapper
                    .deleteById(id);
        } catch (Exception e) {
            throw new ServiceException("删除购物车失败");
        }
    }

    @Override
    public void updateCartNumAndTotalPrice(Integer id, Integer quantity, Integer total) {
        try {
            cartMapper.updateCartNumAndTotalPrice(id, quantity, total);
        } catch (Exception e) {
            throw new ServiceException("更新购物车数量和总价失败");
        }
    }

    @Override
    public List<Product> getCartProductsByIds(List<Integer> ids) {
        try {
            List<Cart> carts = new ArrayList<>();
            for (Integer id : ids) {
                Cart cart = cartMapper.selectById(id);
                carts.add(cart);
            }
            // 获取商品
            List<Integer> productIds = carts.stream().map(Cart::getProductId).collect(Collectors.toList());
            List<Product> products = new ArrayList<>();
            for (Integer productId : productIds) {
                Product product = productMapper.selectById(productId);
                products.add(product);
            }
            return products;
        } catch (Exception e) {
            throw new ServiceException("获取购物车商品失败");
        }
    }

    @Override
    public List<Cart> selectByIds(List<Integer> ids) {
        try {
            List<Cart> carts = new ArrayList<>();
            for (Integer id : ids) {
                Cart cart = cartMapper.selectContainProById(id);
                carts.add(cart);
            }
            return carts;
        } catch (Exception e) {
            throw new ServiceException("查询购物车商品失败");
        }
    }

    @Override
    public void add(Cart cart) {
        try {

            // 判断添加的商品是否存在
            Integer userId = cart.getUserId();
            Integer productId = cart.getProductId();
            Integer status = 1;
            Cart cart1 = cartMapper.selectByUserIdAndProductIdAndStatus(userId, productId, status);
//            Cart cart1 = cartMapper.selectByUserIdAndProductId(userId, productId);

            if (cart1 == null) {
                // 购物车内商品不存在
                cartMapper.add(cart);
                Integer cartId = cart.getId();
                return;
            } else {
                // 购物车内商品存在
                cart1.setQuantity(cart1.getQuantity() + cart.getQuantity());
                cart1.setTotal(cart1.getTotal().add(cart.getTotal()));
                cart1.setUpdateTimeStr(DateUtil.getStringDate(new Date()));
                cartMapper.update(cart1);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("添加购物车商品失败");
        }
    }

    @Override
    public Cart createCart(Cart cart) {
        try {
            cartMapper.createCart(cart);
            return cart;
        } catch (Exception e) {
            throw new ServiceException("创建临时购物车失败");
        }
    }
}

